package org.ws.task.zookeeper.node;

import org.ws.task.exception.DecodeException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public  class NodeDataCodec {

    public static <T> T decode(byte[] data,Class<T> clazz){
        try {
            if(data == null || data.length <= 0){
                return null;
            }
            ObjectInputStream input = new ObjectInputStream(new ByteArrayInputStream(data));
            Object obj = input.readObject();
            if(clazz.isAssignableFrom(obj.getClass())){
                return (T) obj;
            }
            else {
                throw new DecodeException("obj class["+obj.getClass()+"] case [{"+clazz.getName()+"}] error. ");
            }
        } catch (Exception e) {
            throw new DecodeException(e.getMessage(),e);
        }
    }

    public static byte[] encode(Object data){
        try(
                ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
                ObjectOutputStream outputStream = new ObjectOutputStream(arrayOutputStream)
        ) {
            outputStream.writeObject(data);
            outputStream.flush();
            arrayOutputStream.flush();
            return arrayOutputStream.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(),e);
        }
    }
}
